package com.lzx.library.rx;

import android.text.TextUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.PathUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import rxhttp.RxHttpPlugins;
import rxhttp.wrapper.cahce.CacheMode;
import rxhttp.wrapper.callback.Function;
import rxhttp.wrapper.param.Param;

/**
 * 本类所有配置都是非必须的，根据自己需求选择就好
 * User: ljx
 * Date: 2019-11-26
 * Time: 20:44
 */
public class RxHttpManager {

    private volatile static RxHttpManager instance;

    private String access_token = "";


    public static RxHttpManager getInstance() {
        if (instance == null) {
            synchronized (RxHttpManager.class) {
                if (instance == null) {
                    instance = new RxHttpManager();
                }
            }
        }
        return instance;
    }

    public void init(boolean isDebug) {
        RxHttpPlugins.init(new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build())      //自定义OkHttpClient对象  设置读、写、连接超时时间为15s
                .setDebug(isDebug)                //是否开启调试模式，开启后，logcat过滤RxHttp，即可看到整个请求流程日志
                .setCache(new File(PathUtils.getAppDataPathExternalFirst()), 10 * 1024 * 1024, CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE)  //配置缓存目录，最大size及缓存模式
//                .setExcludeCacheKeys(String...)   //设置一些key，不参与cacheKey的组拼
                //.setConverter()         //设置全局的转换器，非必须
                .setOnParamAssembly(new Function<Param<?>, Param<?>>() {
                    @Override
                    public Param<?> apply(Param<?> param) throws Exception {
                        param.add("packageName", AppUtils.getAppPackageName());
                        param.add("version", AppUtils.getAppVersionCode() + "");
                        param.add("deviceType", "android");
                        if (!TextUtils.isEmpty(access_token)) {
                            param.addHeader("access_token", access_token);
                        }
                        return param;
                    }
                });

    }

    /**
     * 设置请求头Token 值
     *
     * @param access_token
     */
    public void setAccessToken(String access_token) {
        this.access_token = access_token;
    }

}
